﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FileConvertPdfSystemBLL;
using FileConvertPdfSystemModel;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Web.Caching;

namespace FileConvertPdfSystemWeb
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        int nClassID = 0;
        bool userLogin = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            //Title = "文档转换Pdf管理系统";
            //if (Request.Params["ClassID"] != null)
            //{
            //    nClassID = Int32.Parse(Request.Params["ClassID"].ToString());
            //}
            //if (!Page.IsPostBack)
            //{
            //    NewsSystem newsSystem = new NewsSystem();
            //    if (nClassID > 0)
            //    {
            //        AspNetPager1.RecordCount = newsSystem.Get_NewsNum(nClassID);
            //        NewClassSystem newClassSystem = new NewClassSystem();
            //        ClassName.Text = "&gt;" + newClassSystem.Get_SintNewClass(nClassID).ClassName;
            //    }
            //    else
            //    {
            //        AspNetPager1.RecordCount = newsSystem.Get_NewsNum();
            //    }
            //}  
            if (!IsPostBack)
            {
                userLogin = false;
                File_Share2 files = new File_Share2();
                Gri.DataSource = files.Get_File();
                Gri.DataBind();
                for(int i=0;i<Gri.Rows.Count;i++){
                ((Button)Gri.Rows[i].Cells[3].FindControl("download")).Enabled = false;
                }
                if (Session["UserNameLogin"]!=null)
                {
                    Response.Redirect("UserLoginSuccess.aspx");
                }

            }


        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Response.Write("<script>alert('test');</script>");
        }

        protected void Gri_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.Gri.PageIndex = e.NewPageIndex;
            File_Share2 files = new File_Share2();
            Gri.DataSource = files.Get_File();
            Gri.DataBind();
            for (int i = 0; i < Gri.Rows.Count; i++)
            {
                ((Button)Gri.Rows[i].Cells[3].FindControl("download")).Enabled = false;
            }


        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            int score;
            string ds = DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()+
                DateTime.Now.Day.ToString();
            string ds1 = "";
            Label1.Text = "";
            Label2.Text = "";
            Label3.Text = "";
            if (TextBox1.Text.ToString() == "")
            {
                Label1.Visible = true;
                Label1.Text = "用户名不能为空！";
                return;
            }
            if (TextBox2.Text.ToString() == "")
            {
                Label2.Visible = true;
                Label2.Text = "密码不能为空！";
                return;
            }
            if (TextBox3.Text.ToString() == "")
            {
                Label3.Visible = true;
                Label3.Text = "验证码不能为空！";
                return;
            }
            UserInformation1 user = new UserInformation1();
            FileConvertPdfSystemModel.UserInformation usermodel = new FileConvertPdfSystemModel.UserInformation();
            usermodel=user.Get_SingUserInformation(TextBox1.Text.ToString());
            string caValue = Convert.ToString(Cache[TextBox1.Text]);
            if (usermodel.UserNameLogin==TextBox1.Text.ToString())
            {
                if (usermodel.Password==TextBox2.Text.ToString())
                {
                    if (caValue == String.Empty)
                    {
                        var sessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                        // 向Cache中插入用户名并设置相关信息
                        HttpContext.Current.Cache.Insert(TextBox1.Text, TextBox1.Text, null, DateTime.MaxValue, sessTimeOut,
                                                         CacheItemPriority.NotRemovable, null);



                        Session["UserNameLogin"] = TextBox1.Text.ToString();
                        score = user.Get_SingUserInformation(TextBox1.Text.ToString()).Score;
                        ds1 = user.Get_SingUserInformation(TextBox1.Text.ToString()).LoadTime.Year.ToString() +
                             user.Get_SingUserInformation(TextBox1.Text.ToString()).LoadTime.Month.ToString() +
                             user.Get_SingUserInformation(TextBox1.Text.ToString()).LoadTime.Day.ToString();
                        if (ds1 != ds)
                        {
                            usermodel.LoadTime = DateTime.Now;
                            usermodel.Score = ++score;
                            user.Update_UserInformation(usermodel);
                        }
                        Response.Write("<script>alert('登录成功');location.href='UserLoginSuccess.aspx';</script>");
                    }
                    else
                    {
                        RegisterStartupScript("", "<script>alert('当前用户已登录')</script>");
                    }
                }
                else
                {
                    Response.Write("<script>alert('密码或验证码错误,请重新输入!');location.href='uploadFileConvertpdf.aspx';</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('没有您输入的用户，请注册！');location.href='uploadFileConvertpdf.aspx';</script>");
            }

            //user.
            userLogin = true;
        }
        private string storefolder = @"c:\PDFConverter\";

        protected void BtnFile_Click(object sender, EventArgs e)
        {
            //FileConvertPdfSystemBLL.LoginUserConvertpdfQueueBLL LoginUserFileDAL = new FileConvertPdfSystemBLL.LoginUserConvertpdfQueueBLL();
            //int FileQueueNum = 0;
            //FileQueueNum = LoginUserFileDAL.Get_LoginUserConvertpdfQueueNum();
            //if (FileQueueNum>0)
            //{
            //    Response.Write("<script>alert('服务器正在转换，请稍后重试!');location.href='uploadFileConvertpdf.aspx';</script>");

            //}
            bool ex = false;
            File_ManageSystemWeb.FileConvertPdf.ConvertFiletoPdf convertopdf = new File_ManageSystemWeb.FileConvertPdf.ConvertFiletoPdf();
            //convertopdf.Url = "http://192.168.196.1/web/pdfService/Service1.asmx";
            if (FileUpload1.HasFile)
            {
                FileInfo file1 = new FileInfo(FileUpload1.PostedFile.FileName);
                if (file1.Extension==".xlsx")
                {
#region         unregister user ,only upload extern .xlsx file
                if (FileUpload1.FileName.Contains(".xlsx"))
                {
                    string sourcefile = storefolder + FileUpload1.FileName;
                    string outputfile = storefolder + FileUpload1.FileName.Replace(".xlsx", ".pdf");
                    //Save original file
                    FileUpload1.SaveAs(sourcefile);
                    //call the converter method
                    //converter.Convert4(sourcefile, outputfile);
                    //service
                    //service.init();
                    ex = convertopdf.str(sourcefile, outputfile);
                    if (ex == false)
                    {
                        Response.Write("<script>alert('convet pdf failed!');location.href='uploadFileConvertpdf.aspx';</script>");
                    }
                    else
                    {
                        Response.Write("<script>alert('convet pdf successful!');location.href='uploadFileConvertpdf.aspx';</script>");
                    }
                    if (File.Exists(outputfile)==true)
                    {
                        Session["file"] = outputfile;
                    }
                    Thread.Sleep(1000);
                    convertopdf.killexcel();
                    System.IO.File.Delete(sourcefile);
                }
#endregion
                }
                else
                {
                    Response.Write("<script>alert('上传文件格式不正确，请选择后缀为.xlsx文件!');location.href='uploadFileConvertpdf.aspx';</script>");

                }
            }
            else
            {
                Response.Write("<script>alert('请选择上传文件!');location.href='uploadFileConvertpdf.aspx';</script>");

            }
        }

        protected void BtnDownFile_Click(object sender, EventArgs e)
        {
            if (Session["file"]!=null)
            {
                //string path = Server.MapPath(@"D:/PDFConverter/") + Session["file"].ToString();
                if (File.Exists(Session["file"].ToString())==false)
                {
                    Response.Write("<script>alert('你是非注册用户，转换服务正在工作,你所提交的文件并未转换不能下载！');location.href='uploadFileConvertpdf.aspx'</script>");
                    return;
                }
                string path = Session["file"].ToString();

                FileInfo fi = new FileInfo(path);

                if (fi.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
                    Response.AddHeader("Content-Length", fi.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Filter.Close();
                    Response.WriteFile(fi.FullName);
                    Response.End();
                }
            }
            else
            {
                Response.Write("<script>alert('你是非注册用户，还没有提交需要转换的文件，不能下载！');location.href='uploadFileConvertpdf.aspx'</script>");
            }
        }
        //protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        //{
        //    BinData();
        //}
        //public void BinData()
        //{
        //    NewsSystem newsSystem = new NewsSystem();
        //    if (nClassID > 0)
        //    {
        //        List_News.DataSource = newsSystem.Get_News(AspNetPager1.StartRecordIndex, AspNetPager1.EndRecordIndex, nClassID);
        //    }
        //    else
        //    {
        //        List_News.DataSource = newsSystem.Get_News(AspNetPager1.StartRecordIndex, AspNetPager1.EndRecordIndex);
        //    }
        //    List_News.DataBind();
        //}
    }
}